package cn.chowx.myjfinal.system.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.chowx.myjfinal.common.BaseModel;
import cn.chowx.myjfinal.common.TableName;
import cn.chowx.myjfinal.common.tree.Node;
import cn.chowx.myjfinal.help.PageHelp;
import cn.chowx.myjfinal.util.DigestUtil;

import com.google.common.base.Strings;
import com.jfinal.kit.JsonKit;

/**
 * 系统用户
 * 
 * @author zcqshine <br>
 *         表结构:<br>
 *         用户信息表<br>
 *         id id - INT(10) Not null 用户id<br>
 *         account account - VARCHAR(50) Not null 登录帐号<br>
 *         password password - VARCHAR(30) Not null 密码<br>
 *         nickName nickName - VARCHAR(50) 昵称<br>
 *         sex sex - TINYINT(1) Not null 性别. 0-男性,1-女性<br>
 *         birthday birthday - DATE 生日<br>
 *         mobile mobile - VARCHAR(20) 手机号码<br>
 *         address address - VARCHAR(100) 地址<br>
 *         email email - VARCHAR(50) 电子邮件<br>
 *         userName userName - VARCHAR(20) 真实姓名<br>
 *         identityNumber identityNumber - VARCHAR(20) 身份证号
 */
@SuppressWarnings("serial")
public class SysUser extends BaseModel<SysUser> {
	public static final SysUser DAO = new SysUser();
	
	/**
	 * 分页查询
	 * @param pageHelp
	 * @return
	 */
	public String findAll(PageHelp pageHelp){
		return getJqGridMap(pageHelp, TableName.SysUser.getTableName());
	}
	
	/**
	 *  获取当前用户的角色列表
	 * @return
	 */
	public List<SysRole> getRolesByUserId(){
		return SysRole.DAO.find("select * from sys_role where id in (select roleId from sys_user_role where userId=?) and status=1 order by id",get("id"));
	}
	
	/**
	 * 根据用户 id 获取角色列表,如果当前用户已经拥有该角色,则设置为 true
	 * @return String
	 */
	public String getRoleJson(int uid){
		List<SysRole> hasRoles = getRolesByUserId(uid);
		List<SysRole> allRoles = SysRole.DAO.findList(1);
		List<Node> nodes = new ArrayList<>();
		for(SysRole role : allRoles){
			Node node = new Node();
			node.setUid(uid);
			node.setId(role.getInt("id"));
			node.setName(role.getStr("roleName"));
			node.setOpen(true);
			if(hasRoles.contains(role)){
				node.setChecked(true);
			}
			node.setPId(role.getInt("parentId"));
			nodes.add(node);
		}
		return JsonKit.toJson(nodes);
	}
	
	/**
	 * 根据用户id 获取角色
	 * @param uid
	 * @return List<SysRole>
	 */
	private List<SysRole> getRolesByUserId(int uid){
		return SysRole.DAO.find("select * from sys_role where id in (select roleId from sys_user_role where userId=?) and status=1 order by id",uid);
	}
	
	/**
	 * 获取当前用户能访问的资源
	 * @return
	 */
	public Set<SysAction> getSysActions(){
		Set<SysAction> actionSet = new HashSet<>();
		actionSet = getRolesByUserId().stream()
							.flatMap(role -> role.getActionsByRoleId().stream())
							.collect(Collectors.toSet());
		return actionSet;
	}
	
	/**
	 * 保存用户并加密用户密码
	 * @return
	 */
	public boolean saveUser(){
		String account = getStr("account");
		String password = getStr("password");
		if(!Strings.isNullOrEmpty(account) && !Strings.isNullOrEmpty(password) && !checkAccount()){
			password = DigestUtil.Md5(password);
			set("password",password);
			return save();
		}
		return false;
	}
	
	/**
	 * 更新用户信息
	 * @param updatePassword 1-修改密码,0-不修改密码
	 * @return
	 */
	public boolean updateUser(int updatePassword){
		String account = getStr("account");
		String password = getStr("password");
		if(updatePassword == 0){
			remove("password");
		}else{
			if(!Strings.isNullOrEmpty(password)){
				password = DigestUtil.Md5(password);
				set("password",password);
			}
		}
		if(!Strings.isNullOrEmpty(account) && checkAccount()){
			return update();
		}
		
		return false;
	}
	
	/**
	 * 检查用户名是否存在.<br>
	 * 存在-true,不存在-false
	 * @return
	 */
	public boolean checkAccount(){
		String account = getStr("account");
		if(!Strings.isNullOrEmpty(account)){
			SysUser user = findFirst("select * from sys_user where `account` = ? limit 1",account);
			if(user != null){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 用户登录. 成功-true, 失败-false
	 * @return boolean
	 */
	public boolean login(){
		String account = getStr("account");
		String password = getStr("password");
		if(!Strings.isNullOrEmpty(account) && !Strings.isNullOrEmpty(password)){
			password = DigestUtil.Md5(password);
			set("password",password);
			SysUser user = DAO.findFirst("select * from sys_user where `account` = ? and `password` = ? limit 1",account,password);
			if(user != null){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 根据登录帐号和密码查询用户. 如果存在就返回SysUser,否则返回null
	 * @param account
	 * @param password
	 * @return
	 */
	public SysUser getSysUserByAccountAndPassword(String account, String password){
		if(!Strings.isNullOrEmpty(account) && !Strings.isNullOrEmpty(password)){
			return DAO.findFirst("select * from sys_user where `account` = ? and `password` = ? limit 1",account,password);
		}
		return null;
	}
	
	/**
	 * 根据帐号查询用户.存在则返回SysUser,否则返回null
	 * @param account
	 * @return
	 */
	public SysUser getSysUserByAccount(String account){
		if(!Strings.isNullOrEmpty(account))
			return findFirst("select * from sys_user where `account` = ? limit 1",account);
		return null;
	}
	
}
